﻿Imports System.Net
Imports System.Text.RegularExpressions

Public Class EastmoneyAPI

    Const REAL_DATA_URL = "https://push2.eastmoney.com/api/qt/stock/details/get?fields1=f1,f2,f3,f4&fields2=f51,f52,f53,f54,f55&fltt=2&pos=-1&secid={bk}.{code}"
    Const DAY_DATA_URL = "https://push2his.eastmoney.com/api/qt/stock/kline/get?secid={bk}.{code}&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=1&fqt=1&end=20500101&lmt=120"

    Public Shared tradingHours As New List(Of (StartTime As TimeSpan, EndTime As TimeSpan)) From {
        (TimeSpan.Parse("09:30"), TimeSpan.Parse("11:30")),
        (TimeSpan.Parse("13:00"), TimeSpan.Parse("15:00"))
    }

    ' 自定义支持完整 Cookie 的 WebClient
    Private Class FullCookieWebClient
        Inherits WebClient

        Private _cookieHeader As String

        Public Sub SetFullCookie(cookieString As String)
            _cookieHeader = cookieString
        End Sub

        Protected Overrides Function GetWebRequest(address As Uri) As WebRequest
            Dim request As HttpWebRequest = CType(MyBase.GetWebRequest(address), HttpWebRequest)
            If Not String.IsNullOrEmpty(_cookieHeader) Then
                request.Headers(HttpRequestHeader.Cookie) = _cookieHeader
            End If
            Return request
        End Function
    End Class

    ' ===== 新方法：使用完整 Cookie =====
    Public Function GetRealData(code As String, fullCookie As String, Optional bk As String = "") As String
        Using wc As New FullCookieWebClient()
            wc.SetFullCookie(fullCookie)
            Return wc.DownloadString(REAL_DATA_URL.Replace("{code}", code).Replace("{bk}", If(bk = "", GetExchangeCode(code).ToString(), bk)))
        End Using
    End Function

    Public Function GetDayData(code As String, fullCookie As String, Optional bk As String = "") As String
        Using wc As New FullCookieWebClient()
            wc.SetFullCookie(fullCookie)
            Return wc.DownloadString(DAY_DATA_URL.Replace("{code}", code).Replace("{bk}", If(bk = "", GetExchangeCode(code).ToString(), bk)))
        End Using
    End Function

    ' ===== 工具方法 =====
    Public Shared Function IsInTradingHours() As Boolean
        Dim currentTime As DateTime = DateTime.Now
        Dim currentDayOfWeek As DayOfWeek = currentTime.DayOfWeek
        Dim currentTimeOfDay As TimeSpan = currentTime.TimeOfDay

        If currentDayOfWeek >= DayOfWeek.Monday AndAlso currentDayOfWeek <= DayOfWeek.Friday Then
            For Each timeRange In tradingHours
                If currentTimeOfDay >= timeRange.StartTime AndAlso currentTimeOfDay <= timeRange.EndTime Then
                    Return True
                End If
            Next
        End If

        Return False
    End Function

    Public Shared Function GetExchangeCode(stockCode As String) As Integer
        Try
            Dim firstThreeDigits As String = stockCode.Substring(0, 3)
            Select Case firstThreeDigits
                Case "600", "601", "603", "605"
                    Return 1 ' 上交所
                Case "000", "001", "002", "003", "004", "300", "301"
                    Return 0 ' 深交所主板
                Case Else
                    Return -1
            End Select
        Catch ex As Exception
            Throw New ArgumentException("无效的股票代码输入", "stockCode", ex)
        End Try
    End Function

End Class